package com.lh.io.bio.file;

import com.lh.io.bio.ExecutorService;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;
import java.util.concurrent.Executor;

public class Server {

    public static void main(String[] args) {

        try {
            ServerSocket socket = new ServerSocket(8888);

            ExecutorService executorService = new ExecutorService();
            Executor executor = executorService.getExecutor();
            while (true) {
                Socket accept = socket.accept(); //会阻塞，知道接收到客户端请求
                executor.execute(() -> {
                    try {
                        DataInputStream is = new DataInputStream(accept.getInputStream());
                        String suffix = is.readUTF();
                        File file = new File("C:\\Users\\17838330192\\Desktop\\" + UUID.randomUUID().toString() + "." + suffix);
                        FileOutputStream os = new FileOutputStream(file);

                        int readLine = 0;
                        byte[] buffer = new byte[1024];
                        while ((readLine = is.read(buffer)) >0){
                            os.write(buffer,0,readLine);
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
